package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
	common "jihe.common"
	"jihe.common/protos/auth_server"
	"jihe.common/protos/auth_server/proto"
	"jihe.common/resp"
)

func VerifyToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		if common.Configer.Runmode == "dev" {
			c.Next()
			return
		}
		token := c.GetHeader("Authorization")
		uid := c.GetHeader("Uid")
		out, err := auth_server.VerifyToken(c, &proto.VerifyTokenReq{
			Token: token,
			Uid:   uid,
		})
		if err != nil {
			resp.RespCode(c, http.StatusUnauthorized)
			c.Abort()
			return
		}
		if !out.Result {
			resp.RespCode(c, http.StatusUnauthorized)
			c.Abort()
			return
		}
		c.Set("uid", uid)
		c.Next()
	}
}
